//
//  DetailViewController.m
//  Funny
//
//  Created by dllo on 15/10/29.
//  Copyright © 2015年 King. All rights reserved.
//

#import "DetailViewController.h"
#import "Detail.h"
#import "HeaderTableViewCell.h"
#import "DetailTableViewCell.h"
#import "PictureViewController.h"
#import "WebDetailViewController.h"
#import "DetailWeatherViewController.h"
#import "MapViewController.h"

@interface DetailViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray *arr;
@property (nonatomic, strong) Detail *detailModel;
@property (nonatomic, strong) UIBarButtonItem *collectButton;
@property (nonatomic, strong) DataBase *dataBase;
@property (nonatomic, assign) BOOL isOpen;
@property (nonatomic, strong) NSArray *dbArr;
@property (nonatomic, strong) MBProgressHUD *hub;

@end

@implementation DetailViewController

- (void)viewWillDisappear:(BOOL)animated
{
    [self.dataBase close];
}

- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBarHidden = NO;
    [self.dataBase open];
    self.dbArr = [self.dataBase getDetailAll];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"详情";
    [self handleData];
    [self.view addSubview:self.tableView];
    self.arr = [NSMutableArray arrayWithObjects:@"详情介绍", @"详细地址", @"天气状况", @"购买须知", nil];
    self.collectButton = [[UIBarButtonItem alloc]initWithImage:nil style:UIBarButtonItemStylePlain target:self action:@selector(collectButtonClick:)];

    [self.dataBase open];
    self.dbArr = [self.dataBase getDetailAll];
    if (_dbArr.count == 0) {
         self.collectButton.image = [UIImage imageNamed:@"nocollect@3x.png"];
        _isOpen = NO;
    }
    for (Detail *model in _dbArr) {
        if ([model.cityID isEqualToNumber:self.productId]) {
            self.collectButton.image = [UIImage imageNamed:@"collected@3x.png"];
            [_collectButton setTintColor:[UIColor redColor]];
            _isOpen = YES;
            break;
        }
        else{
            self.collectButton.image = [UIImage imageNamed:@"nocollect@3x.png"];
            self.collectButton.tintColor = [UIColor whiteColor];
            _isOpen = NO;
        }
    }
    UIBarButtonItem *shareButton = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"share.png"] style:UIBarButtonItemStyleDone target:self action:@selector(shareButtonAction:)];
    NSArray *arr = @[shareButton,self.collectButton];
    self.navigationItem.rightBarButtonItems = arr;
    
    BOOL result = [self.dataBase open];
    if (result) {
        [self.dataBase creatDetailTable];
    }
    self.dbArr = [self.dataBase getDetailAll];
    
}

- (NSArray *)dbArr{
    if (!_dbArr) {
        self.dbArr = [NSArray array];
    }
    return _dbArr;
}

- (DataBase *)dataBase
{
    if (!_dataBase) {
        self.dataBase = [DataBase shareDataBase];
    }
    return _dataBase;
}

- (void)collectButtonClick:(UIButton *)btn
{
    self.hub = [[MBProgressHUD alloc]initWithView:self.view];
    if (_isOpen == YES) {
        [self.dataBase deleteDetailDataWithModel:self.detailModel];
        self.collectButton.image = [UIImage imageNamed:@"nocollect@3x.png"];
        self.collectButton.tintColor = [UIColor whiteColor];
        _hub.labelText = @"删除成功";
        _isOpen = NO;
    }else
    {
        if (self.detailModel.cityID == nil) {
            _hub.labelText = @"未加载完成";
        }
        else{
            [self.dataBase insertDetailDataWithModel:self.detailModel];
            self.collectButton.image = [UIImage imageNamed:@"collected@3x.png"];
            self.collectButton.tintColor = [UIColor redColor];
            _hub.labelText = @"收藏成功";
            _isOpen = YES;
        }
    }
    [self.view addSubview:_hub];
    [_hub showAnimated:NO whileExecutingBlock:^{
        sleep(1);
    } completionBlock:^{
        [_hub removeFromSuperview];
    }];

}

#pragma mark -分享
- (void)shareButtonAction:(id)sender
{
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100 * W, 100 * H)];
    NSString *url1 = @"http://api.mxtrip.cn/api/place/getPlace?placeid=";
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    [imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://cdn.yaochufa.com/%@",self.detailModel.imageurl]] placeholderImage:[UIImage imageNamed:@"chartlet_image_traning@2x.png"]];
    [shareParams SSDKSetupShareParamsByText:[NSString stringWithFormat:@"#分享来自FHY的美好事物#  %@%@",self.detailModel.productName,url1]
                                     images:imageView.image
                                        url:[NSURL URLWithString:url1]
                                      title:@"分享标题"
                                       type:SSDKContentTypeImage];
    
    [ShareSDK showShareActionSheet:sender
                             items:nil
                       shareParams:shareParams
               onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                   switch (state) {
                       case SSDKResponseStateBegin:
                       {
                           NSLog(@"开始分享");
                       }
                           break;
                       case SSDKResponseStateSuccess:
                       {
                           
                           UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"分享成功" message:nil preferredStyle:1];
                           UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                               ;
                           }];
                           [alter addAction:okAction];
                           [self presentViewController:alter animated:YES completion:^{
                               
                           }];
                       }
                           break;
                       case SSDKResponseStateFail:
                       {
                           UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"分享失败" message:nil preferredStyle:1];
                           UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                               ;
                           }];
                           [alter addAction:okAction];
                           [self presentViewController:alter animated:YES completion:^{
                               
                           }];
                       }
                           break;
                       case SSDKResponseStateCancel:
                       {
                           
                           UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"分享取消" message:nil preferredStyle:1];
                           UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                               ;
                           }];
                           [alter addAction:okAction];
                           [self presentViewController:alter animated:YES completion:^{
                               
                           }];
                       }
                           break;
                       default:
                           break;
                   }
               }];
}

#pragma mark -dataArray懒加载
- (NSArray *)dataArray
{
    if (!_dataArray) {
        self.dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

#pragma mark -创建tableView
- (UITableView *)tableView
{
    if (!_tableView) {
        self.tableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = NO;
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"tableView"];
        _tableView.showsVerticalScrollIndicator = NO;
        [_tableView registerClass:[HeaderTableViewCell class] forCellReuseIdentifier:@"header"];
        [_tableView registerClass:[DetailTableViewCell class] forCellReuseIdentifier:@"detail"];
    }
    return _tableView;
}

#pragma mark -tableView方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return ScreenWidth / 3 * 2;
    }
    return 50;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 1) {
        return 4;
    }
    return 1;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        HeaderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"header"];
        [cell.bgImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://cdn.yaochufa.com/%@",[[[[self.dataArray firstObject] imageList] firstObject] objectForKey:@"url"]]] placeholderImage:[UIImage imageNamed:@"chartlet_image_traning@2x.png"]];
        cell.titleLable.text = self.detailModel.productName;
        cell.infoLable.text = self.detailModel.appSubTitle;
        return cell;
    }
    if (indexPath.section == 1) {
        DetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"detail"];
        [cell.iconImageView setImage:[UIImage imageNamed:[NSString stringWithFormat:@"icon%ld.png", (long)indexPath.row]]];
        cell.titlelable.text = [self.arr objectAtIndex:indexPath.row];
        cell.rightimageView.image = [UIImage imageNamed:@"next.png"];
        
        return cell;
    }
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableView"];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0)
    {
        PictureViewController *pic = [[PictureViewController alloc]init];
        pic.imageListArray = self.detailModel.imageList;
        pic.productName = self.detailModel.productName;
        [self.navigationController pushViewController:pic animated:YES];
    }
    if (indexPath.section == 1 && (indexPath.row == 0||indexPath.row == 3))
    {
        WebDetailViewController *web = [[WebDetailViewController alloc]init];
        switch (indexPath.row)
        {
            case 0:
                web.addressStr = self.detailModel.productIntroduction;
                break;
                
            case 3:
                web.addressStr = self.detailModel.packageDetial;
                break;
            default:
                break;
        }
        [self.navigationController pushViewController:web animated:YES];
    }
    else if(indexPath.section == 1 &&indexPath.row == 2)
    {
        DetailWeatherViewController *weather = [[DetailWeatherViewController alloc]init];
        weather.productId = self.detailModel.cityID;
        [self.navigationController pushViewController:weather animated:YES];
    }
    else if (indexPath.section == 1 && indexPath.row == 1)
    {
        
        MapViewController *map = [[MapViewController alloc]init];
        map.latitude = [self.detailModel.latitude doubleValue];
        map.longitude = [self.detailModel.longitude doubleValue];
        [self.navigationController pushViewController:map animated:YES];
    }
}

#pragma mark -处理数据
- (void)handleData
{
    NSString *str = [NSString stringWithFormat:@"http://appapi.yaochufa.com/v2/Product/GetProductInfoById?productId=%@&machineCode=00000000-58ca-002b-e3ba-8a9569d38c36&version=4.4.0&system=android&channel=nearme", self.productId];
    [HandleData handleDataWithUrl:str completion:^(id data) {
        self.detailModel = [Detail modelWithDic:[data objectForKey:@"data"]];
        self.detailModel.cityID = [[data objectForKey:@"data"] objectForKey:@"productId"];
        self.detailModel.imageurl = [[[[data objectForKey:@"data"] objectForKey:@"imageList"] firstObject]objectForKey:@"url"];
        [self.dataArray addObject:_detailModel];
        [self.tableView reloadData];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
